<template>
  <div class="material-detail-container">
    <!-- 资料基本信息 -->
    <el-card class="material-info-card">
      <div class="material-header">
        <div class="material-title">
          <h1>{{ material.title }}</h1>
          <div class="material-meta">
            <el-tag size="small">{{ material.category?.name }}</el-tag>
            <span class="upload-time">上传时间：{{ formatDate(material.createdAt) }}</span>
            <span class="download-count">
              <el-icon><Download /></el-icon>
              {{ material.downloads }} 次下载
            </span>
          </div>
        </div>
        <div class="material-actions">
          <el-button-group>
            <el-button
              type="primary"
              :disabled="!userStore.isLoggedIn"
              @click="handleDownload(false)"
            >
              下载（{{ material.price }} 虚拟币）
            </el-button>
            <el-button
              type="primary"
              :disabled="!userStore.isLoggedIn"
              @click="handleDownload(true)"
            >
              无水印下载（{{ material.price + material.noWatermarkPrice }} 虚拟币）
            </el-button>
          </el-button-group>
        </div>
      </div>

      <!-- 资料标签 -->
      <div class="material-tags" v-if="material.tags?.length">
        <el-tag
          v-for="tag in material.tags"
          :key="tag.id"
          :color="tag.color"
          effect="plain"
          style="margin-right: 8px"
        >
          {{ tag.name }}
        </el-tag>
      </div>

      <!-- 资料描述 -->
      <div class="material-description">
        <h3>资料描述</h3>
        <p>{{ material.description || '暂无描述' }}</p>
      </div>

      <!-- 资料信息 -->
      <div class="material-details">
        <h3>资料信息</h3>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="文件类型">
            {{ material.fileType?.toUpperCase() }}
          </el-descriptions-item>
          <el-descriptions-item label="文件大小">
            {{ formatFileSize(material.fileSize) }}
          </el-descriptions-item>
          <el-descriptions-item label="带水印价格">
            {{ material.price }} 虚拟币
          </el-descriptions-item>
          <el-descriptions-item label="无水印价格">
            {{ material.price + material.noWatermarkPrice }} 虚拟币
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-card>

    <!-- 预览区域 -->
    <el-card class="preview-card">
      <template #header>
        <div class="preview-header">
          <h3>资料预览</h3>
          <el-tag type="warning" v-if="material.fileType !== '.pdf'">
            非PDF文件仅支持缩略图预览
          </el-tag>
        </div>
      </template>
      <div class="preview-content">
        <template v-if="isImage">
          <img :src="previewUrl" :alt="material.title" class="preview-image" />
        </template>
        <template v-else-if="isPDF">
          <PDFPreview :pdf-url="previewUrl" />
        </template>
        <template v-else>
          <div class="thumbnail-preview">
            <img 
              :src="thumbnailUrl" 
              :alt="material.title" 
              class="preview-thumbnail"
              @click="showFullPreview = true"
            />
            <p class="preview-hint">点击查看完整文件</p>
          </div>

          <el-dialog
            v-model="showFullPreview"
            :title="material.title"
            width="80%"
          >
            <div class="full-preview">
              <img 
                v-if="isImage"
                :src="previewUrl" 
                :alt="material.title"
                class="full-image"
              />
              <div v-else class="unsupported-preview">
                <el-icon><Document /></el-icon>
                <p>不支持在线预览此文件类型</p>
                <p>请下载后查看</p>
              </div>
            </div>
          </el-dialog>
        </template>
      </div>
    </el-card>

    <!-- 相关推荐 -->
    <el-card class="related-materials-card">
      <template #header>
        <div class="related-header">
          <h3>相关推荐</h3>
        </div>
      </template>
      <el-row :gutter="20">
        <el-col
          v-for="item in relatedMaterials"
          :key="item.id"
          :xs="24"
          :sm="12"
          :md="8"
          :lg="6"
        >
          <el-card
            class="related-item-card"
            shadow="hover"
            @click="goToMaterial(item.id)"
          >
            <img :src="item.thumbnailPath" :alt="item.title" class="related-thumbnail" />
            <div class="related-info">
              <h4>{{ item.title }}</h4>
              <div class="related-meta">
                <span class="related-price">{{ item.price }} 虚拟币</span>
                <span class="related-downloads">
                  <el-icon><Download /></el-icon>
                  {{ item.downloads }}
                </span>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </el-card>

    <!-- 下载确认对话框 -->
    <el-dialog
      v-model="downloadDialogVisible"
      :title="downloadType === 'watermark' ? '下载确认' : '无水印下载确认'"
      width="30%"
    >
      <div class="download-confirm">
        <p>您当前的虚拟币余额：{{ userStore.user?.virtualCoins || 0 }}</p>
        <p>本次下载将消耗：{{ downloadCost }} 虚拟币</p>
        <template v-if="downloadCost > (userStore.user?.virtualCoins || 0)">
          <el-alert
            title="余额不足"
            type="error"
            description="您的虚拟币余额不足，请先充值"
            show-icon
          />
        </template>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="downloadDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="confirmDownload"
            :disabled="downloadCost > (userStore.user?.virtualCoins || 0)"
          >
            确认下载
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Download, ArrowLeft, ArrowRight, Minus, Plus, Refresh, Loading, Document } from '@element-plus/icons-vue'
import { useUserStore } from '@/store/user'
import { getMaterialById, getRelatedMaterials, generateDownloadLink } from '@/api/material'
import PDFPreview from '@/components/PDFPreview.vue'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

// 资料数据
const material = ref({})
const relatedMaterials = ref([])

// 下载相关状态
const downloadDialogVisible = ref(false)
const downloadType = ref('watermark')
const downloadCost = computed(() => {
  if (!material.value) return 0
  return downloadType.value === 'watermark'
    ? material.value.price
    : material.value.price + material.value.noWatermarkPrice
})

// 预览相关计算属性
const showFullPreview = ref(false)

const isImage = computed(() => {
  const imageTypes = ['.jpg', '.jpeg', '.png', '.gif']
  return imageTypes.includes(material.value.fileType?.toLowerCase())
})

const isPDF = computed(() => {
  return material.value.fileType?.toLowerCase() === '.pdf'
})

const previewUrl = computed(() => {
  if (!material.value.filePath) return ''
  return `/api/materials/${material.value.id}/preview`
})

const thumbnailUrl = computed(() => {
  if (!material.value.thumbnailPath) return '/images/default-thumbnail.jpg'
  // 过滤掉via.placeholder.com的URL
  if (material.value.thumbnailPath.includes('via.placeholder.com')) {
    return '/images/default-thumbnail.jpg'
  }
  return `/api/materials/${material.value.id}/thumbnail`
})

// 加载资料详情
const loadMaterialDetail = async () => {
  try {
    const res = await getMaterialById(route.params.id)
    material.value = res.data.material
    loadRelatedMaterials()
  } catch (error) {
    console.error('加载资料详情失败:', error)
    ElMessage.error('加载资料详情失败')
  }
}

// 加载相关推荐
const loadRelatedMaterials = async () => {
  try {
    const res = await getRelatedMaterials(material.value.id)
    relatedMaterials.value = res.data.materials
  } catch (error) {
    console.error('加载相关推荐失败:', error)
  }
}

// 处理下载
const handleDownload = (noWatermark) => {
  if (!userStore.isLoggedIn) {
    router.push('/login')
    return
  }
  
  downloadType.value = noWatermark ? 'no-watermark' : 'watermark'
  downloadDialogVisible.value = true
}

// 确认下载
const confirmDownload = async () => {
  try {
    const res = await generateDownloadLink(material.value.id, {
      noWatermark: downloadType.value === 'no-watermark'
    })
    
    // 更新用户虚拟币余额
    userStore.user.virtualCoins = res.data.remainingCoins
    
    // 创建一个隐藏的a标签来触发下载
    const link = document.createElement('a')
    link.href = res.data.downloadUrl
    link.target = '_blank'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    
    downloadDialogVisible.value = false
    ElMessage.success('下载已开始')
    
    // 更新资料下载次数
    material.value.downloads += 1
  } catch (error) {
    console.error('下载失败:', error)
    if (error.response?.status === 400) {
      ElMessage.warning(error.response.data.message)
    } else {
      ElMessage.error(error.response?.data?.message || '下载失败')
    }
  }
}

// 跳转到其他资料详情页
const goToMaterial = (id) => {
  router.push(`/material/${id}`)
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric'
  })
}

// 格式化文件大小
const formatFileSize = (size) => {
  if (!size) return '0 B'
  const units = ['B', 'KB', 'MB', 'GB']
  let index = 0
  let fileSize = size

  while (fileSize >= 1024 && index < units.length - 1) {
    fileSize /= 1024
    index++
  }

  return `${fileSize.toFixed(2)} ${units[index]}`
}

// 页面加载时获取资料详情
onMounted(() => {
  loadMaterialDetail()
})
</script>

<style scoped>
.material-detail-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.material-info-card {
  margin-bottom: 20px;
}

.material-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
}

.material-title h1 {
  margin: 0 0 10px 0;
  font-size: 24px;
  color: #303133;
}

.material-meta {
  display: flex;
  align-items: center;
  gap: 20px;
  color: #909399;
  font-size: 14px;
}

.material-tags {
  margin: 20px 0;
}

.material-description {
  margin: 20px 0;
}

.material-description h3 {
  margin-bottom: 10px;
  color: #303133;
}

.material-description p {
  color: #606266;
  line-height: 1.6;
}

.preview-card {
  margin-bottom: 20px;
}

.preview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.preview-content {
  min-height: 300px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.preview-image {
  max-width: 100%;
  max-height: 500px;
  object-fit: contain;
}

.thumbnail-preview {
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;
}

.thumbnail-preview:hover {
  transform: scale(1.05);
}

.preview-thumbnail {
  max-width: 200px;
  max-height: 200px;
  object-fit: contain;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.preview-hint {
  margin-top: 10px;
  color: #606266;
  font-size: 14px;
}

.full-preview {
  text-align: center;
}

.full-image {
  max-width: 100%;
  max-height: 70vh;
  object-fit: contain;
}

.unsupported-preview {
  padding: 40px;
  text-align: center;
  color: #909399;
}

.unsupported-preview .el-icon {
  font-size: 60px;
  margin-bottom: 20px;
}

.related-materials-card {
  margin-bottom: 20px;
}

.related-item-card {
  cursor: pointer;
  transition: transform 0.3s;
}

.related-item-card:hover {
  transform: translateY(-5px);
}

.related-thumbnail {
  width: 100%;
  height: 150px;
  object-fit: cover;
}

.related-info {
  padding: 10px;
}

.related-info h4 {
  margin: 0 0 10px 0;
  font-size: 14px;
  color: #303133;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.related-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #909399;
  font-size: 12px;
}

.download-confirm {
  text-align: center;
}

.download-confirm p {
  margin: 10px 0;
}
</style>